<?php
class cliActions extends sfActions
{
	public function executeIndex($request) 
	{
		$this->checkUser($request);
	}

	public function executeCommand($request)
	{
		$command = $this->validCommand($request->getParameter('command', 'list'));
		
		try 
		{
			$this->checkUser($request);
			
			$cli = new sfFilesystem();
			$this->getResponse()->setContent($this->formatOutput($cli->sh(sfConfig::get('sf_root_dir') . DIRECTORY_SEPARATOR . 'symfony ' . $command)));
		}
		catch(sfException $ex)
		{
			$this->getResponse()->setContent($ex);
		}
		
		return sfView::NONE;
	}
	
	public function formatOutput($command)
	{
		$ret = utf8_encode($command);
		
		return $ret;
	}
	
	public function checkUser($request)
	{
		if(sfConfig::get('app_cli_from'))
		{
			if (!in_array(@$_SERVER['REMOTE_ADDR'], sfConfig::get('app_cli_from')))
			{
				throw new sfException('Ip restriction [' . $_SERVER['REMOTE_ADDR'] . '] : you cannot access to this module');
			}
		}
		else
		{
			$key = $request->getParameter('k');
			
			$c_key = sfConfig::get('app_cli_key');
			
			if($c_key == $key)
			{
				return true;
			}
			else
			{
				throw new sfException('Key invalid');
			}
		}
	}
    
    public function validCommand($command)
    {
        return escapeshellarg($command);
    }
}
?>